<?php


namespace app\controller\admin\activity;

use app\common\model\activity\NewActivityCouponRelevance;
use app\common\repositories\store\coupon\StoreCouponUserRepository;
use app\common\repositories\user\UserRepository;
use crmeb\basic\BaseController;
use app\common\repositories\article\ArticleCategoryRepository;
use app\common\repositories\activity\NewActivityRepository;
use crmeb\jobs\SendNewActivityPeopleCouponJob;
use think\App;
use app\validate\admin\ActivityValidate;
use think\facade\Db;
use think\facade\Queue;

class NewActivity extends BaseController
{
    /**
     * @var NewActivityRepository
     */
    protected $repository;

    /**
     * activity constructor.
     * @param App $app
     * @param NewActivityRepository $repository
     */
    public function __construct(App $app,NewActivityRepository $repository)
    {
        parent::__construct($app);
        $this->repository = $repository;
    }


    /**
     * @return mixed
     * @author: fupeng
     * @day: 2024/1/28
     */
    public function getList()
    {
        [$page, $limit] = $this->getPage();

        $where = $this->request->params(['title','date']);

        return app('json')->success($this->repository->search($where, $page, $limit));
    }

    /**
     * @param ActivityValidate $validate
     * @param ArticleCategoryRepository $repository
     * @return mixed
     * @author: fupeng
     * @day: 2024/1/29
     */
    public function create(ActivityValidate $validate,NewActivityCouponRelevance $repository)
    {
        $res =  $this->repository->getNewActivity(['is_del'=>0,'type'=>3]);
        if($res){
            return app('json')->fail('已存在活动,无法创建新活动');
        }
        $data = $this->checkParams($validate);
        $arr = $this->request->params([['arr_coupon',[]]]);
        $res= Db::transaction(function () use ($data,$arr,$repository) {
            $start_time = strtotime($data['start_time']);
            $end_time = strtotime($data['end_time']);
            if($start_time <time() && $end_time > time() ){
                $data['state'] = 1;
            }
            $res = $this->repository->create($data);
            $arr_insert =[];
            if($data['coupon_id']){
                $arr_insert[]=[
                    'new_activity_id'=> $res->new_activity_id,
                    'coupon_id'=>$data['coupon_id'],
                    'num'=> 0,
                    'image'=>null,
                    'sort'=>0,
                ];
            }
            foreach ($arr['arr_coupon'] as $k=>$v){
                $arr_insert[]=[
                    'new_activity_id'=> $res->new_activity_id,
                    'coupon_id'=>$v['coupon_id'],
                    'num'=> $v['num'],
                    'image'=>$v['image'],
                    'sort'=>$k+1,
                ];
            }
          $repository->insertAll($arr_insert);
          return $res;
        });
        if($res->send_type == 1 && strtotime($res->start_time) <= time()){
            Queue::push(SendNewActivityPeopleCouponJob::class, $res->toArray());
        }
        return  app('json')->success('发布成功');
    }


    /**
     * @param ActivityValidate $validate
     * @param ArticleCategoryRepository $repository
     * @return mixed
     * @author: fupeng
     * @day: 2024/1/29
     */
    public function update($id){
        $data = $this->request->params(['title', 'pop_style','rule']);
        if (!$this->repository->exists($id))
            return app('json')->fail('数据不存在');
        $this->repository->update($id,$data);
        return  app('json')->success('修改成功');
    }

    public function switchStatus($id)
    {
        $status = $this->request->param('status', 0) == 1 ? 1 : 0;
        if(!$this->repository->get($id)) return app('json')->fail('数据不存在');
        if($status == 1){
            $res =  $this->repository->getNewActivity(['is_del'=>0,'type'=>1,'not_id'=>$id]);
            if($res){
                return app('json')->fail('已经有活动开启，无法开启该活动');
            }
        }
        $this->repository->switchStatus($id, ['status' => $status]);
        return app('json')->success('修改成功');
    }


    /**
     * @param $id
     * @return mixed
     * @author: fupeng
     * @day: 2024/1/29
     * 删除
     */
    public function delete($id)
    {
        if (!$this->repository->exists($id))
            return app('json')->fail('数据不存在');
        $this->repository->update($id, ['is_del' => 1]);
        return  app('json')->success('删除成功');
    }


    /**
     * @return mixed
     * @author: fupeng
     * @day: 2024/1/28
     * 领取记录
     */
    public function claimRecord(StoreCouponUserRepository $repository)
    {
        [$page, $limit] = $this->getPage();
        $where = $this->request->params(['username','date','new_activity_id']);
        return app('json')->success($repository->getNewActivityList($where, $page, $limit));
    }

    /**
     * @param ActivityValidate $validate
     * @return array
     * @author Qinii
     */
    public function checkParams(ActivityValidate $validate)
    {
        $data = $this->request->params([['coupon_id', 0],'title', 'start_time', 'end_time', 'pop_style',['is_open', 0],'rule','send_type']);
        $validate->check($data);
        return $data;
    }

}
